/**
 * 依赖注入容器
 * 职责：
 * 1. 服务注册和获取
 * 2. 单例和工厂模式支持
 * 3. 循环依赖检测
 * 4. 生命周期管理
 */
export class DIContainer {
    private services = new Map<string, ServiceDefinition>();
    private singletons = new Map<string, any>();
    private resolutionStack = new Set<string>();

    /**
     * 注册服务
     * @param token 服务标识
     * @param factory 工厂函数
     * @param options 注册选项
     */
    register<T>(
        token: string, 
        factory: (container: DIContainer) => T, 
        options: ServiceOptions = {}
    ): void {
        if (this.services.has(token)) {
            console.warn(`Service ${token} is already registered. Overwriting...`);
        }

        this.services.set(token, {
            factory,
            singleton: options.singleton ?? false,
            dependencies: options.dependencies ?? [],
            lifecycle: options.lifecycle ?? 'lazy'
        });

        console.log(`Service registered: ${token} (singleton: ${options.singleton})`);

        // 如果是急切加载，立即实例化
        if (options.lifecycle === 'eager' && options.singleton) {
            this.get<T>(token);
        }
    }

    /**
     * 获取服务实例
     * @param token 服务标识
     * @returns 服务实例
     */
    get<T>(token: string): T {
        const serviceDefinition = this.services.get(token);
        if (!serviceDefinition) {
            throw new Error(`Service ${token} is not registered`);
        }

        // 检测循环依赖
        if (this.resolutionStack.has(token)) {
            const stack = Array.from(this.resolutionStack).join(' -> ');
            throw new Error(`Circular dependency detected: ${stack} -> ${token}`);
        }

        // 如果是单例且已经实例化，直接返回
        if (serviceDefinition.singleton && this.singletons.has(token)) {
            return this.singletons.get(token);
        }

        // 开始解析
        this.resolutionStack.add(token);

        try {
            console.log(`Resolving service: ${token}`);
            const instance = serviceDefinition.factory(this);

            // 如果是单例，缓存实例
            if (serviceDefinition.singleton) {
                this.singletons.set(token, instance);
                console.log(`Singleton service cached: ${token}`);
            }

            return instance;
        } finally {
            // 清理解析栈
            this.resolutionStack.delete(token);
        }
    }

    /**
     * 检查服务是否已注册
     * @param token 服务标识
     * @returns 是否已注册
     */
    has(token: string): boolean {
        return this.services.has(token);
    }

    /**
     * 注销服务
     * @param token 服务标识
     */
    unregister(token: string): void {
        this.services.delete(token);
        this.singletons.delete(token);
        console.log(`Service unregistered: ${token}`);
    }

    /**
     * 清理所有单例实例
     */
    clearSingletons(): void {
        console.log('Clearing all singleton instances...');
        this.singletons.clear();
    }

    /**
     * 清理容器
     */
    clear(): void {
        console.log('Clearing DI container...');
        this.services.clear();
        this.singletons.clear();
        this.resolutionStack.clear();
    }

    /**
     * 获取注册的服务列表
     */
    getRegisteredServices(): string[] {
        return Array.from(this.services.keys());
    }

    /**
     * 获取单例服务列表
     */
    getSingletonServices(): string[] {
        return Array.from(this.singletons.keys());
    }

    /**
     * 批量注册服务
     * @param registrations 服务注册配置
     */
    registerBatch(registrations: ServiceRegistration[]): void {
        console.log(`Batch registering ${registrations.length} services...`);
        
        for (const registration of registrations) {
            this.register(
                registration.token, 
                registration.factory, 
                registration.options
            );
        }
        
        console.log('Batch registration completed');
    }

    /**
     * 验证所有已注册服务的依赖
     */
    validateDependencies(): ValidationResult {
        const errors: string[] = [];
        const warnings: string[] = [];

        for (const [token, definition] of this.services) {
            for (const dependency of definition.dependencies) {
                if (!this.has(dependency)) {
                    errors.push(`Service ${token} depends on unregistered service: ${dependency}`);
                }
            }
        }

        return {
            isValid: errors.length === 0,
            errors,
            warnings
        };
    }
}

/**
 * 服务定义接口
 */
interface ServiceDefinition {
    factory: (container: DIContainer) => any;
    singleton: boolean;
    dependencies: string[];
    lifecycle: 'lazy' | 'eager';
}

/**
 * 服务注册选项
 */
export interface ServiceOptions {
    singleton?: boolean;
    dependencies?: string[];
    lifecycle?: 'lazy' | 'eager';
}

/**
 * 服务注册配置
 */
export interface ServiceRegistration {
    token: string;
    factory: (container: DIContainer) => any;
    options?: ServiceOptions;
}

/**
 * 验证结果
 */
interface ValidationResult {
    isValid: boolean;
    errors: string[];
    warnings: string[];
}

/**
 * 默认容器实例
 */
export const container = new DIContainer();
